package cn.com.callback

import cn.com.elite.EliteBean
import cn.com.elite.Util
import cn.com.kh.KHDBConfig
import com.alibaba.fastjson.JSONObject
import com.wisdge.dataservice.Result
import org.apache.commons.logging.Log
import org.apache.commons.logging.LogFactory

import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse
import cn.com.kh.KHUtil

/**
 * 生成动态页面短链接的API
 */

public class apiShortenLink implements ServiceBackInvoke {
    private static final Log log = LogFactory.getLog(apiShortenLink.class);

    public String doCallBack(EliteBean eliteBean, HttpServletRequest request, HttpServletResponse response) {
        String DOMAIN = KHDBConfig.getAPIURL(eliteBean, "NGS-OuterDomain");

        response.setCharacterEncoding("UTF-8");

        String getMethod = request.getMethod();
        log.debug("getMethod:" + getMethod);

        //获取所有参数名
        Enumeration e = request.getParameterNames();
        while (e.hasMoreElements()) {
            //获取当前参数名
            String parameterName = (String) e.nextElement();
            //再通过request.getParameter("")的方法来获取对应参数名的值
            log.debug(parameterName + ": " + request.getParameter(parameterName));
        }

        if (getMethod.equals("GET")) {

            String dynid = request.getParameter("dynid");
            String userid = request.getParameter("userid");
            String usertype = request.getParameter("usertype");
            String woid = request.getParameter("woid");
            String taskid = request.getParameter("taskid");
            String expand = request.getParameter("expand");
            String cbtype = request.getParameter("cbtype");
            String opsource = request.getParameter("opsource");
            log.debug("原始Get请求参数-dynid:" + dynid + " userid:" + userid + " usertype:" + usertype + " woid:" + woid + " taskid:" + taskid + " expand:" + expand + " cbtype:" + cbtype + " opsource:" + opsource);

            String checkNullInfo = KHUtil.isNullMSG("dynid", dynid) + KHUtil.isNullMSG("userid", userid);
            log.debug("非空校验检查结果:" + checkNullInfo);
            if (!KHUtil.isNull(checkNullInfo)) {
                if (cbtype.equals("redirect")) {
                    response.sendRedirect(DOMAIN + "/htmls/500/index.jsp");
                } else {
                    return JSONObject.toJSONString(new Result(Result.ERROR, checkNullInfo));
                }

            } else {

                try {
                    String url = DOMAIN + "/S";

                    // 获取短码标准入参
                    JSONObject content = new JSONObject();
                    content.put("at", "dyn2");
                    content.put("mt", "r");
                    content.put("q", "sp");
                    content.put("ai", dynid);

                    // 客制化参数部分
                    JSONObject requestParams = new JSONObject();
                    requestParams.put("WOID", woid);
                    requestParams.put("TASKID", taskid);
                    requestParams.put("EXPAND", expand);
                    requestParams.put("USERID", userid);
                    requestParams.put("USERTYPE", usertype);
                    requestParams.put("OPSOURCE", opsource);
                    content.put("params", requestParams);

                    // 封装调用参数
                    JSONObject params = new JSONObject();
                    params.put("ttl", 0);
                    params.put("content", content.toJSONString());
                    log.debug("封装调用参数params:" + params.toString());

                    // 发起调用
                    Map<String, String> headMap = new HashMap<String, String>();
                    headMap.put("Content-Type", "application/json");

                    String resultBody = Util.doHttpPostUseHead(url, params.toString(), "UTF-8", 5000, 0, headMap);
                    log.debug("调用返回resultBody:" + resultBody);

                    // 解析调用参数
                    JSONObject resultJson = JSONObject.parseObject(resultBody);
                    if (resultJson.getInteger("code") == 1) {
                        log.debug("调用NGS生成短码成功！" + resultJson.getString("value"));

                        if (cbtype.equals("redirect")) {
                            response.sendRedirect(DOMAIN + "/m/nl?" + resultJson.getString("value"));
                        } else {
                            return JSONObject.toJSONString(new Result(Result.SUCCESS, DOMAIN + "/m/nl?" + resultJson.getString("value")));
                        }
                    } else {

                        log.warn("调用NGS生成短码错误！" + resultJson.getString("message"));

                        if (cbtype.equals("redirect")) {
                            response.sendRedirect(DOMAIN + "/htmls/500/index.jsp");
                        } else {
                            return JSONObject.toJSONString(new Result(Result.WARN, "调用NGS生成短码错误！", resultJson.getString("message")));
                        }
                    }

                } catch (Exception e1) {
                    log.error("调用NGS生成短码链接异常：", e1);

                    if (cbtype.equals("redirect")) {
                        response.sendRedirect(DOMAIN + "/htmls/500/index.jsp");
                    } else {
                        return JSONObject.toJSONString(new Result(Result.ERROR, "调用NGS生成短码链接异常：" + e1.getMessage()));
                    }
                }
            }

        } else {

            log.error("HTTP请求调用类型错误，接口调用失败：" + getMethod);
            return JSONObject.toJSONString(new Result(Result.ERROR, "HTTP请求调用类型错误，接口调用失败：" + getMethod));
        }
    }
}
